package org.itest.foo;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Title: ScheduledThreadPoolExecutorTest</p>
 * <p>Date: 2019/11/11 </p>
 * <p>Description: </p>
 *
 * @author xinhe
 */
public class ScheduledThreadPoolExecutorTest {

    public static void main(String[] args) {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
        BusinessTask task = new BusinessTask();
        //1秒后开始执行任务，以后每隔2秒执行一次
        executorService.scheduleWithFixedDelay(task, 1000, 2000, TimeUnit.MILLISECONDS);
    }

    private static class BusinessTask implements Runnable {

        private static AtomicInteger count = new AtomicInteger(0);

        @Override
        public void run() {
            //捕获所有的异常，保证定时任务能够继续执行
            try {
                System.out.println("任务开始...");
                int i = count.incrementAndGet();
                System.out.println("执行次数：" + i);
                if (i==2){
                    throw new RuntimeException("业务异常");
                }
                //doBusiness();
                System.out.println("任务结束...");
            } catch (Throwable e) {
                // donothing
                e.printStackTrace();
                throw e;
            }
        }
    }
}
